import { ProForm } from '@ant-design/pro-components';
import { Button, Form, message, Space } from 'antd';
import { useContext, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import React from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import ProFormItemDynamic from '../ProFormItemDynamic';
import { ApiInfo, ApiType, FormType, TableRecord, ProTableContexteValue, EventFormType, Forms, FormInfo } from '../../utils/types';
import { dataSource } from '../../utils/dataSource';

import { initConfig } from './config';
///开始删除
import { ProTableContext } from '../../../Context/ProTableContext';
import { dealApiSelectDetail } from '@/utils/dataDeal';
import lodash from 'lodash';
///结束删除

const ProFormDynamic = (props: any) => {
  ///开始删除
  // 全局数据源
  const proTableContexteValue: ProTableContexteValue = useContext<ProTableContexteValue>(ProTableContext); // 获取公共数据
  ///结束删除

  // 处理字段数据，该给默认值给默认值，该隐藏隐藏
  const getFormFields = (columns: any[]): any[] => {
    if (!columns || Object.keys(columns).length === 0) return [];
    console.debug('getFormFields', columns);
    columns.forEach((column: any) => {
      column.formFieldType = column.formFieldType ?? 'ProFormText'; // 默认赋formFieldType类型为ProFormText
      column.placeholder = column.placeholder ?? '请输入';
      column.tooltip = column.tooltip ?? '';
      column.value = column.value ?? '';
    });
    if (props.isTable) {
      return columns.filter((column: any) => {
        return !column.dataIndex.includes('table-'); // 过滤数据
      });
    } else {
      return [...columns];
    }
  };
  ///开始删除
  const getFormData = (columns: any[]): any => {
    let formData: any = {};
    if (!columns || Object.keys(columns).length === 0) return formData;
    columns.forEach((column: any) => {
      // 排除
      if (props.isTable && !column.dataIndex.includes('table-')) {
        formData[column['dataIndex']] = column['value'];
      } else {
        formData[column['dataIndex']] = column['value'];
      }
    });
    return formData;
  };
  ///结束删除

  const baseFormRef = useRef<ProFormInstance>(); // 表单
  let [config, setConfig] = new Array();

  ///开始删除
  if (props.isTable) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    [config, setConfig] = useState<any>(initConfig);
  } else if (props.dynamic) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    [config, setConfig] = useState<any>(props.config);
  } else {
    ///结束删除
    // eslint-disable-next-line react-hooks/rules-of-hooks
    [config, setConfig] = useState<any>(initConfig);
    ///开始删除
  }
  ///结束删除

  const dealFormData = async () => {
    const type: FormType = props.formType;
    switch (type) {
      case 'detail':
      case 'edit':
      case 'add': {
        // 详情和编辑都需要先查询出来
        const key = config.dataSource.keyInfo.key; // 主键
        let value = ''; // 主键值

        ///开始删除
        if (props.isTable) {
          ///结束删除
          const currentTableRecord: TableRecord = props.currentTableRecord;
          if (!currentTableRecord || Object.keys(currentTableRecord).length === 0) {
            return {};
          }
          value = currentTableRecord.record[key];
          ///开始删除
        } else {
          value = config.dataSource.keyInfo.value;
        }
        ///结束删除

        const apiType: ApiType = 'detail';
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        apiInfo.parameter[key] = value;
        const dataDetail: any = await dataSource(apiType, apiInfo, '');
        // console.debug('dealFormData', apiType, apiInfo, dataDetail);
        if (!dataDetail) return {};
        return dataDetail;
      }
      default:
        return {};
    }
  };

  ///开始删除
  // 如果是表格内嵌的动态表单
  if (props.dynamic || props.isTable) {
    // setting更新时需要监听eventFormType，获取到的数据同步到表单中
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(() => {
      const eventFormType: EventFormType = props.eventFormType;
      if (eventFormType.includes('eventReloadForm')) {
        const getDataSourceAndDeal = async () => {
          const dataDetail = await dealFormData();
          if (!dataDetail) return;
          const columns = dealApiSelectDetail(dataDetail); // 生成列数据
          const newFormFields = getFormFields(columns); // 生成表单项

          const formType = props.formType;
          const newForms = props.config.forms;
          newForms[formType].formFields = newFormFields;

          const newConfig = { ...props.config, forms: { ...newForms } };

          setConfig(newConfig);
          proTableContexteValue.setFormInfo(newConfig);

          baseFormRef.current?.setFieldsValue(dataDetail); // 更新表单数据
          console.debug('ProFormDynamic props.eventFormType', dataDetail, newFormFields, config);
        };
        getDataSourceAndDeal();
      }
    }, [props.eventFormType]);
    // 更新信息同步到表单中
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(() => {
      // 更新表单
      const formType: FormType = props.formType;
      console.debug('ProFormDynamic React.useEffect props.config', props.config, formType, config);
      const newFormFields = getFormFields(props.config.forms[formType]?.formFields); // 生成表单项
      const newForms: Forms = props.config.forms;
      if (!newForms[formType]) {
        // 如果不存在此类型
        newForms[formType] = {} as FormInfo;
      }
      newForms[formType].formFields = [...newFormFields];

      const newConfig = { ...props.config, forms: { ...newForms } };

      setConfig(newConfig);
      proTableContexteValue.setFormInfo(newConfig);

      const newFormData = getFormData(props.config.forms[formType].formFields); // 生成表单项
      baseFormRef.current?.setFieldsValue(newFormData); // 更新表单数据
    }, [props.config]);
  } else {
    // 如果是单纯的生成出来的表单
    ///结束删除
    const getDataSourceAndDeal = async () => {
      const dataDetail = await dealFormData();
      if (!dataDetail) return;
      baseFormRef.current?.setFieldsValue(dataDetail); // 更新表单数据
      // console.debug('ProFormDynamic getDataSourceAndDeal', dataDetail, newFormFields, config);
    };
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(() => {
      // 更新表单
      const newConfig = { ...config };

      newConfig.formType = props.formType;
      newConfig.currentTableRecord = props.currentTableRecord;
      newConfig.dataSource = props.dataSource;
      console.debug('ProFormDynamic props.formType', newConfig);
      setConfig(newConfig);
      getDataSourceAndDeal();
    }, [props.formType, props.currentTableRecord]);
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(() => {
      // 更新表单
      getDataSourceAndDeal();
    }, []);
    ///开始删除
  }
  ///结束删除

  const onFormSubmit = () => {
    const type: FormType = props.formType;
    // console.debug('onFormSubmit', type);
    switch (type) {
      case 'edit': {
        // console.debug('onFormSubmit edit');
        const apiType: ApiType = 'update'; // 修改
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        baseFormRef.current?.validateFieldsReturnFormatValue?.().then((values) => {
          apiInfo.body = values;
          // console.log('校验表单并返回格式化后的所有数据：', apiInfo);
          dataSource(apiType, apiInfo, '修改成功');
        });
        break;
      }
      case 'add': {
        const apiType: ApiType = 'add'; // 保存
        const apiInfo: ApiInfo = config.dataSource.apiList[apiType];
        baseFormRef.current?.validateFieldsReturnFormatValue?.().then((values) => {
          apiInfo.body = values;
          // console.debug('校验表单并返回格式化后的所有数据：', apiInfo);
          dataSource(apiType, apiInfo, '新增成功');
        });
        break;
      }
    }
  };

  ///开始删除
  if (props.isTable) {
  } else if (props.dynamic) {
  } else {
    ///结束删除
    if (Object.keys(config).length === 0) {
      message.warn('没有配置表单。');
      return <></>;
    }
    ///开始删除
  }
  ///结束删除
  console.debug('ProFormDynamic', 'props.config:', props.config, 'config:', config, 'formType:', props.formType, 'currentTableRecord:', props.currentTableRecord);
  return (
    <>
      <ProForm
        formRef={baseFormRef}
        labelCol={config.forms[props.formType]?.formConfig?.layout === 'inline' ? undefined : config.forms[props.formType]?.formConfig?.labelCol} // inline 模式下不能设置值，否则显示异常
        wrapperCol={config.forms[props.formType]?.formConfig?.layout === 'inline' ? undefined : config.forms[props.formType]?.formConfig?.wrapperCol} // inline 模式下不能设置值，否则显示异常
        grid={config.forms[props.formType]?.formConfig?.grid}
        layout={config.forms[props.formType]?.formConfig?.layout}
        readonly={config.forms[props.formType]?.formConfig?.readonly}
        size={config.forms[props.formType]?.formConfig?.size}
        submitter={{
          // 完全自定义整个区域
          render: (formProps: any, doms: any) => {
            // console.log(props);
            return [
              config.forms[props.formType]?.formConfig?.showReset || config.forms[props.formType]?.formConfig?.showSubmit ? (
                <Form.Item
                  wrapperCol={config.forms[props.formType]?.formConfig?.layout === 'horizontal' ? config.forms[props.formType]?.formConfig?.submitWrapperCol : undefined}
                  key="submit"
                >
                  <Space>
                    {config.forms[props.formType]?.formConfig?.showReset ? (
                      <Button type="default" key="rest" onClick={() => formProps.reset()}>
                        {config.forms[props.formType]?.formConfig?.resetText}
                      </Button>
                    ) : null}

                    {config.forms[props.formType]?.formConfig?.showSubmit ? (
                      <Button type="primary" onClick={() => formProps.submit()}>
                        {config.forms[props.formType]?.formConfig?.submitText}
                      </Button>
                    ) : null}
                  </Space>
                </Form.Item>
              ) : null,
            ];
          },
          onSubmit: () => {
            onFormSubmit();
          },
        }}
        onValuesChange={(_: any, values: any) => {
          // console.debug(_, values);
        }}
      >
        {config.forms[props.formType]?.formFields?.map((formFieldInfo: any, index: number) => {
          return <ProFormItemDynamic formFieldInfo={formFieldInfo} key={index} />;
        })}
      </ProForm>
    </>
  );
};
ProFormDynamic.propTypes = {
  config: PropTypes.object,
  formType: PropTypes.string,
  ///开始删除
  dynamic: PropTypes.bool, // 是否动态组件
  eventFormType: PropTypes.string,
  ///结束删除
  isTable: PropTypes.bool, // 是否表格表单
  currentTableRecord: PropTypes.object,
};
export default ProFormDynamic;
// export default ProFormDynamic;
